<template>
  <div class="message">
    <el-popover placement="bottom" :width="310" trigger="click">
      <template #reference>
        <el-badge :value="mailCount" :max="99" :show-zero="false" class="item">
          <i :class="'iconfont icon-xiaoxi'" class="toolBar-icon"></i>
        </el-badge>
      </template>
      <el-tabs v-model="activeName">
        <el-tab-pane :label="`通知(${noticeMailList.length})`" name="first">
          <div v-if="noticeMailList.length > 0" class="message-list">
            <div v-for="item in noticeMailList" :key="item.id" class="message-item" @click="handleOpen(item.id, item.mailType)">
              <img src="@/assets/images/msg03.png" class="message-icon" />
              <div class="message-content">
                <span class="message-title">{{ item.title }}</span>
                <span class="message-date">{{ item.createTime }}</span>
              </div>
            </div>
          </div>
          <div v-else class="message-empty">
            <img src="@/assets/images/notData.png" alt="notData" />
            <div>暂无通知</div>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="`公告(${announcementMailList.length})`" name="second">
          <div v-if="announcementMailList.length > 0" class="message-list">
            <div
              v-for="item in announcementMailList"
              :key="item.id"
              class="message-item"
              @click="handleOpen(item.id, item.mailType)"
            >
              <img src="@/assets/images/msg01.png" class="message-icon" />
              <div class="message-content">
                <span class="message-title">{{ item.title }}</span>
                <span class="message-date">{{ item.createTime }}</span>
              </div>
            </div>
          </div>
          <div v-else class="message-empty">
            <img src="@/assets/images/notData.png" alt="notData" />
            <div>暂无公告</div>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="`我的(${privateLetterMailList.length})`" name="third">
          <div v-if="privateLetterMailList.length > 0" class="message-list">
            <div
              v-for="item in privateLetterMailList"
              :key="item.id"
              class="message-item"
              @click="handleOpen(item.id, item.mailType)"
            >
              <img src="@/assets/images/msg02.png" class="message-icon" />
              <div class="message-content">
                <span class="message-title">{{ item.title }}</span>
                <span class="message-date">{{ item.createTime }}</span>
              </div>
            </div>
          </div>
          <div v-else class="message-empty">
            <img src="@/assets/images/notData.png" alt="notData" />
            <div>暂无私信</div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-popover>

    <el-dialog v-model="dialogVisible" :title="mailTitle" width="40%">
      <div v-html="mailMessage"></div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type { SysMail } from "@/api/interface";
import { ref, computed, onMounted } from "vue";
import { getUserNoReadMailApi, getMailMessageApi } from "@/api/modules/system";
import { HubConnectionBuilder, HttpTransportType } from "@microsoft/signalr";
import { useUserStore } from "@/stores/modules/user";
import { ElNotification } from "element-plus";

const activeName = ref("first");
const dialogVisible = ref(false);
const mailTitle = ref("");
const mailMessage = ref();
const noticeMailList = ref<SysMail.ShortResult[]>([]);
const announcementMailList = ref<SysMail.ShortResult[]>([]);
const privateLetterMailList = ref<SysMail.ShortResult[]>([]);
const mailCount = computed(() => {
  let count = 0;
  count += noticeMailList.value.length;
  count += announcementMailList.value.length;
  count += privateLetterMailList.value.length;
  return count;
});

const userStore = useUserStore();

/** 打开消息详情 */
const handleOpen = (mailId: string, mailType: number) => {
  dialogVisible.value = true;
  getMailMessageApi(mailId).then(({ data }) => {
    mailTitle.value = data.title;
    mailMessage.value = data.message;

    // 在对应列表中删除已读消息
    switch (mailType) {
      case 0:
        noticeMailList.value = noticeMailList.value.filter(item => item.id !== mailId);
        break;
      case 1:
        announcementMailList.value = announcementMailList.value.filter(item => item.id !== mailId);
        break;
      case 2:
        privateLetterMailList.value = privateLetterMailList.value.filter(item => item.id !== mailId);
        break;
    }
  });
};

const connection = new HubConnectionBuilder()
  .withUrl("/canrocnet/hub/internal-mail", {
    transport: HttpTransportType.WebSockets,
    accessTokenFactory: () => `${userStore.token}`
  })
  .build();
connection
  .start()
  .then(() => console.log("ws连接成功！"))
  .catch(err => console.log(err));
connection.on("ReceiveMessage", (msg: any) => {
  // 检查新消息类型，更新消息列表
  if (msg.mailType === 0) {
    noticeMailList.value.unshift(msg);
  } else if (msg.mailType === 1) {
    announcementMailList.value.unshift(msg);
  } else if (msg.mailType === 2) {
    privateLetterMailList.value.unshift(msg);
  }

  // 弹窗提示有新消息
  ElNotification({
    title: "新消息",
    message: msg.title,
    type: "success",
    position: "bottom-right",
    duration: 5000
  });
});

onMounted(() => {
  getUserNoReadMailApi().then(({ data }) => {
    data?.forEach(item => {
      switch (item.mailType) {
        case 0:
          noticeMailList.value.push(item);
          break;
        case 1:
          announcementMailList.value.push(item);
          break;
        case 2:
          privateLetterMailList.value.push(item);
          break;
      }
    });
  });
});
</script>

<style scoped lang="scss">
.message-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 260px;
  line-height: 45px;
}
.message-list {
  display: flex;
  flex-direction: column;
  .message-item {
    display: flex;
    align-items: center;
    padding: 20px 0;
    cursor: pointer;
    border-bottom: 1px solid var(--el-border-color-light);
    &:last-child {
      border: none;
    }
    .message-icon {
      width: 40px;
      height: 40px;
      margin: 0 20px 0 5px;
    }
    .message-content {
      display: flex;
      flex-direction: column;
      .message-title {
        margin-bottom: 5px;
      }
      .message-date {
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }
    }
  }
}
</style>
